package com.searchcloud.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpMethod;
import org.springframework.util.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
 *@author:ike
 *@function:微信Token刷新任务
 *@creatTime:17:18 2017/10/25
 **/
public class WeiXinTokenRefreshTask {
    public void getToken(){

        System.out.println("开始获取token");
        String result=null;
        try {
            URL url=new URL(ServerUrlUtils.GET_ACCESS_TOKEN_URL);
            HttpURLConnection connection= (HttpURLConnection) url.openConnection();
            connection.setRequestMethod(String.valueOf(HttpMethod.GET));
            connection.setConnectTimeout(5000);
            connection.setUseCaches(false);
            connection.connect();
            if (connection.getResponseCode()==HttpURLConnection.HTTP_OK){
                InputStream inputStream = connection.getInputStream();
                ByteArrayOutputStream bos=new ByteArrayOutputStream();
               byte[] buffer=new byte[1024];
               int length;
               while ((length=inputStream.read(buffer))!=-1){
                   bos.write(buffer,0,length);
               }
               connection.disconnect();
               inputStream.close();
               bos.close();
               result=new String(bos.toByteArray());
               if (!StringUtils.isEmpty(result)){
                   JSONObject jsonObject = JSON.parseObject(result);
                   ConstantUtils.ACCESS_TOKEN=jsonObject.getString("access_token");
                   System.out.println("token:"+ConstantUtils.ACCESS_TOKEN);
               }
            }
        } catch (IOException e) {

            e.printStackTrace();
            result=e.getMessage();
            System.err.println("获取Token出错了:"+result);
        }

    }

}
